package com.suneee.base.sendmsg.mail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.suneee.base.sendmsg.ISendMsgService;
import com.suneee.base.sendmsg.bean.SendMsgBean;
import com.suneee.cloud.admin.resources.AdminError;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;

public class SendEMailMsgServiceImpl implements ISendMsgService {

	private Properties props = null;
	// 邮件服务器
	private String mailHost = null;
	// 邮件端口号
	private int mailPort = 0;
	// 邮件是否需要鉴权
	private String mailAuth = null;
	// 邮件用户名称
	private String mailUserName = null;
	// 邮件密码
	private String mailUserPwd = null;

	private final Logger logger = Logger.getLogger(SendEMailMsgServiceImpl.class);

	/**
	 * 初始化邮件的属性
	 */
	private void init() {
		props = new Properties();
		if (StringUtils.isEmpty(mailHost)) {
			// 抛出邮件没有服务器的异常
			throw ErrorUtils.wrap(AdminError.MAIL_ERROR_NOT_HOST);
		}
		if (mailPort <= 0) {
			// 如果没有配置端口，默认为端口是25
			mailPort = 25;
		}
		if (StringUtils.isEmpty(mailAuth)) {
			// 如果没有配置验证，需要看是否配置密码，如果不配置，则默认不需要验证
			if (StringUtils.isEmpty(mailUserPwd)) {
				// 默认不需要验证
				mailAuth = "false";
			} else {
				// 如果配置密码，则默认为true
				mailAuth = "true";
			}
		}
		props.put("mail.smtp.host", mailHost.trim());
		props.put("mail.smtp.auth", mailAuth);
		props.put("mail.smtp.port", mailPort);
	}

	@Override
	public boolean sendMsg(SendMsgBean sendBean) {
		long s = System.currentTimeMillis();
		long e1 = 0;
		if (null == props || props.isEmpty()) {
			init();
		}

		try {
			// SendMsgBean mailBean = (SendMsgBean) sendBean;

			// 创建发送邮件的会话
			Session session = Session.getDefaultInstance(props,new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(mailUserName,mailUserPwd);
				}
			});
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为111:" + (e1 - s) + "毫秒 或"+ ((e1 - s) / 1000) + "秒");
			// session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			// 设置发件人
			String sendPerson = sendBean.getSendPerson();
			sendPerson = !StringUtils.isEmpty(sendPerson) ? sendPerson.trim(): !StringUtils.isEmpty(mailUserName) ? mailUserName.trim() : "";
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为3222:" + (e1 - s) + "毫秒 或"
					+ ((e1 - s) / 1000) + "秒");
			if (StringUtils.isEmpty(sendPerson)) {
				throw ErrorUtils.wrap(AdminError.MAIL_ERROR_NOT_SEND_ADDRESS);
			}

			message.setFrom(new InternetAddress(sendPerson));
			// 设置收件人
			message.setRecipients(RecipientType.TO,changStingToAddres(sendBean.getRecievePerson()));
			// 设置抄送
			// if (StringUtils.isNotEmptyStr(mailBean.getCopyPersion()))
			// {
			// message.setRecipients(RecipientType.CC,
			// changStingToAddres(mailBean.getCopyPersion()));
			// }
			// // 密送
			// if (StringUtils.isNotEmptyStr(mailBean.getSecretPersion()))
			// {
			// message.setRecipients(RecipientType.BCC,
			// changStingToAddres(mailBean.getSecretPersion()));
			// }
			if (!StringUtils.isEmpty(sendBean.getSubject())) {
				message.setSubject(sendBean.getSubject());
			}
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为3333:" + (e1 - s) + "毫秒 或"+ ((e1 - s) / 1000) + "秒");
			if (!StringUtils.isEmpty(sendBean.getContent())) {
				MimeMultipart multiPart = new MimeMultipart("related");
				MimeBodyPart htmlBodyPart = new MimeBodyPart();
				htmlBodyPart.setContent(sendBean.getContent(),"text/html;charset=utf-8");
				multiPart.addBodyPart(htmlBodyPart);
				// 设置邮件内容
				message.setContent(multiPart);
			}
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为44444:" + (e1 - s) + "毫秒 或"+ ((e1 - s) / 1000) + "秒");
			message.setSentDate(new Date(System.currentTimeMillis()));
			Transport.send(message);
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为555555:" + (e1 - s) + "毫秒 或"+ ((e1 - s) / 1000) + "秒");
			return true;
		} catch (Exception e) {
			logger.error("发送邮件失败：" + e.getMessage());
			logger.debug("发送邮件失败", e);
		} finally {
			e1 = System.currentTimeMillis();
			logger.debug("发送邮件需要的时间为:" + (e1 - s) + "毫秒 或" + ((e1 - s) / 1000)+ "秒");
		}

		return false;
	}
	
	/**
	 * 将字符串转换成地址
	 * @param person
	 * @return
	 */
	private InternetAddress[] changStingToAddres(String person) {
		if (StringUtils.isEmpty(person)) {
			throw ErrorUtils.wrap(AdminError.MAIL_ERROR_NOT_ADDRESS);
		}
		List<String> receiveList = stringToList(person,",");
		List<InternetAddress> addressList = new ArrayList<>();
		InternetAddress address = null;
		for (String addr : receiveList) {
			try {
				if (!StringUtils.isEmpty(addr)) {
					address = new InternetAddress(addr.trim());
					addressList.add(address);
				}
			} catch (Exception e) {
				logger.error("邮件地址错误：" + addr + " 错误信息为：" + e.getMessage());
				logger.debug("邮件地址错误：" + addr, e);
				throw ErrorUtils.wrap(AdminError.MAIL_ERROR_NOT_ADDRESS);
			}
		}
		if (addressList.isEmpty()) {
			throw ErrorUtils.wrap(AdminError.MAIL_ERROR_NOT_ADDRESS);
		}
		InternetAddress[] addresArr = new InternetAddress[addressList.size()];
		addressList.toArray(addresArr);

		return addresArr;
	}
	
	public static List<String> stringToList(String str, String split)
	{
		String[] arr = str.split(split);
		return Arrays.asList(arr);
	}

	public String getMailHost() {
		return mailHost;
	}

	public void setMailHost(String mailHost) {
		this.mailHost = mailHost;
	}

	public int getMailPort() {
		return mailPort;
	}

	public void setMailPort(int mailPort) {
		this.mailPort = mailPort;
	}

	public String getMailAuth() {
		return mailAuth;
	}

	public void setMailAuth(String mailAuth) {
		this.mailAuth = mailAuth;
	}

	public String getMailUserName() {
		return mailUserName;
	}

	public void setMailUserName(String mailUserName) {
		this.mailUserName = mailUserName;
	}

	public String getMailUserPwd() {
		return mailUserPwd;
	}

	public void setMailUserPwd(String mailUserPwd) {
		this.mailUserPwd = mailUserPwd;
	}

	
}
